﻿using UnityEngine;
using Framework;

public class FPSCalculator : Singleton<FPSCalculator>
{
    private int _fpsMeasureInterval = 0;
    private readonly Heap<int, MinHeapComparator> _minHeap = new Heap<int, MinHeapComparator>(new MinHeapComparator());
    private readonly Heap<int, MaxHeapComparator> _maxHeap = new Heap<int, MaxHeapComparator>(new MaxHeapComparator());
    private int _currentMediumFps;
    public int MediumFps;
    
    public void Tick(float deltaTime)
    {
        int fps = Mathf.FloorToInt(1 / deltaTime);
        if (fps >= _currentMediumFps)
        {
            _minHeap.Push(fps);
            if (_minHeap.size() - _maxHeap.size() > 1)
            {
                _maxHeap.Push(_currentMediumFps);
                _currentMediumFps = _minHeap.pop();
            }
        }
        else
        {
            _maxHeap.Push(fps);
            if (_maxHeap.size() - _minHeap.size() > 1)
            {
                _minHeap.Push(_currentMediumFps);
                _currentMediumFps = _maxHeap.pop();
            }
        }

        _fpsMeasureInterval++;

        if (_fpsMeasureInterval >= 200)
        {
            MediumFps = _currentMediumFps;

            _minHeap.Clear();
            _maxHeap.Clear();
            _currentMediumFps = 0;
            _fpsMeasureInterval = 0;
        }
    }
}
